import { defineStore } from 'pinia';
import { login, register, deleteUser, updateUserInfo, changeUserPassword, blindRegister } from '@/api/User';
import router from '@/router';
import { reactive } from 'vue';
import { showNotify, showSuccessToast, showFailToast } from 'vant';
import { removeStorage } from '@/utils/localStorage';

// 踩坑：后端返回的 data是 NULL ！！！
export default defineStore('userStore', () => {
    const userInfo = reactive({
        userid: '',
        username: '',
        nickname: '',
        preeJsid: '',
        // 0代表盲人，1代表志愿者，默认为盲人
        types: 0,
        email: '',
        isLogin: false,
        phone: '',
        address: '',
        postsList: []
    })

    // 登录
    const userLogin = async (username, password) => {
        // console.log("-----------------------", userInfo.preeJsid);
        const temp = userInfo.preeJsid;
        const { code, data } = await login(username, password)
        if (data !== null && code !== 0) {
            Object.keys(data).forEach(key => {
                if (Object.prototype.hasOwnProperty.call(userInfo, key)) {
                    userInfo[key] = data[key]
                }
            })
            userInfo.isLogin = true
            showNotify({
                type: "success",
                message: "登录成功，3s后返回首页",
                duration: 3000,
            });
            userInfo.preeJsid = temp
            // console.log(userInfo.preeJsid)
            setTimeout(() => {
                // router.push({ name: 'homePage' })
                location.href = '/home-page'
            }, 2000);
        }
    }

    // 设置peerJsId
    const setPeerJsId = (id) => {
        userInfo.preeJsid = id
        // console.log(userInfo.preeJsid)
    }

    // 盲人注册
    const blindRegisterTo = async () => {
        const { code, data } = await blindRegister()
        // console.log(username,password,email);
        if (code == 9999) {
            // localStorage.removeItem("userStore")
            Object.keys(data).forEach(key => {
                if (Object.prototype.hasOwnProperty.call(userInfo, key)) {
                    userInfo[key] = data[key]
                }
            })
            userInfo.isLogin = true
            showSuccessToast('注册成功');

            setTimeout(() => {
                router.push({ name: 'homePage' });
                // location.href = '/home-page'
            }, 2000);
        } else {
            showFailToast('注册失败，请稍后再试')
        }
    }

    // 注册
    const userRegister = async (username, password, types, email) => {
        const { code } = await register(username, password, types, email)
        // console.log(username,password,types,email);
        // 注册成功
        // console.log(code !== 0)

        // 踩坑：后端返回的 data是 NULL ！！！
        if (code !== 0) {
            showSuccessToast('注册成功');
            showNotify({
                type: "success",
                message: "注册成功，3s后返回登录",
                duration: 3000,
            });
            setTimeout(() => {
                sessionStorage.clear("regis");
                router.push({ name: 'UserLogin' });
            }, 3000);
        }
    }

    // 退出
    const userLogout = () => {
        userInfo.isLogin = false
        removeStorage('userStore')

        showNotify({
            type: "success",
            message: "退出成功，3s后返回首页",
            duration: 3000,
        });
        setTimeout(() => {
            router.replace({ name: 'homePage' })
        }, 3000);
    }

    // 注销
    const userDelete = async (userid) => {
        userInfo.isLogin = false

        const { code } = await deleteUser(userid)
        if (code === 1) {
            removeStorage('userStore')
            showNotify({
                type: "success",
                message: "注销成功，期待与您再次相见",
                duration: 3000,
            });
        }
        setTimeout(() => {
            router.replace({ name: 'homePage' })
        }, 3000);
    }

    // 更新用户信息
    const userUpdate = async (data) => {
        // 因为传递过来的是响应式对象，得先转成普通对象
        const obj = JSON.parse(JSON.stringify(data))
        // 向后端发送请求
        const { code, msg } = await updateUserInfo(obj)
        if (code === 1 && msg === 'success') {
            // 更新本地数据
            Object.keys(data).forEach(key => {
                if (Object.prototype.hasOwnProperty.call(userInfo, key)) {
                    userInfo[key] = data[key]
                }
            })
            showSuccessToast('更新成功')
        } else {
            showFailToast('更新失败，请稍后再试')
        }

    }

    // 用户修改密码
    const userChangePassword = async (userId, oldPassword, newPassword) => {
        // console.log(userId, oldPassword, newPassword)
        userInfo.isLogin = false
        const { code, msg } = await changeUserPassword(userId, oldPassword, newPassword)
        if (code === 1 && msg === 'success') {
            showSuccessToast('密码修改成功')

            // 密码修改成功，跳转到登录页面
            setTimeout(() => {
                router.push({ name: 'UserLogin' })
            }, 2000)
        } else {
            showFailToast(msg)
        }
    }

    return {
        userInfo,
        userLogin,
        userRegister,
        userLogout,
        userDelete,
        userUpdate,
        userChangePassword,
        setPeerJsId,
        blindRegisterTo
    }
}, { persist: true })